package com.jl.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jl.BeanUtils;
import com.jl.EmptyUtils;

import java.util.List;

/**
 * bean工具
 */
public class PlusBeanUtils extends BeanUtils {

    /**
     * 分页复制
     *
     * @param resultClass 返回集合泛型class
     * @param ipage       分页对象
     * @param <T>         泛型
     * @return
     */
    public static <T> IPage<T> copy(Class<T> resultClass, IPage<?> ipage) {
        List<T> result = copy(resultClass, ipage.getRecords());
        IPage<T> page = new Page<T>()
                .setRecords(result)
                .setPages(ipage.getPages())
                .setTotal(ipage.getTotal())
                .setSize(ipage.getSize())
                .setCurrent(ipage.getCurrent());
        return page;
    }

    /**
     * 自定义分页对象转mp分页对象
     *
     * @param JPageBean 自定义分页对象
     * @return
     */
    public static <T> IPage<T> toIPage(PageBean<T> JPageBean) {
        Page<T> page = copy(Page.class, JPageBean);
        if (EmptyUtils.check(JPageBean.getOrders())) {
            page.setOrders(copy(OrderItem.class, JPageBean.getOrders()));
        }
        return page;
    }

    /**
     * mp分页对象转自定义分页对象
     *
     * @param iPage mp分页对象
     * @param <T>
     * @return
     */
    public static <T> PageBean<T> toJPageBean(IPage<T> iPage) {
        PageBean<T> JPageBean = new PageBean()
                .setCurrent(iPage.getCurrent())
                .setSize(iPage.getSize())
                .setTotal(iPage.getTotal())
                .setOrders(iPage.orders())
                .setRecords(iPage.getRecords())
                .setOptimizeCountSql(iPage.optimizeCountSql())
                .setSearchCount(iPage.searchCount());
        return JPageBean;
    }

    /**
     * mp分页对象转自定义分页对象
     *
     * @param tClass 泛型
     * @param iPage  mp分页对象
     * @param <T>
     * @return
     */
    public static <T> PageBean<T> toJPageBean(Class<T> tClass, IPage<?> iPage) {
        List<T> list = copy(tClass, iPage.getRecords());
        PageBean<T> JPageBean = new PageBean()
                .setCurrent(iPage.getCurrent())
                .setSize(iPage.getSize())
                .setTotal(iPage.getTotal())
                .setOrders(iPage.orders())
                .setRecords(list)
                .setOptimizeCountSql(iPage.optimizeCountSql())
                .setSearchCount(iPage.searchCount());
        return JPageBean;
    }
}
